﻿package  PinballCode{
	
	// Bar Class
	public class Bar extends Wall{
	
	// Attributes
	public var L:int;	// Length of the bar (X)
	public var M:int = 100;	// unifrom Mass
	private var pivot:Vertex;
	private var T:Number;
	private var I:Number;
	private var nonPivot;
	public var W:Number = 0;
	private var A:Number = 0;
	private var left:Boolean;
	private var G:int = -1000;
	
	public var theta:Number = 0;	
		
	// constructor code
	public function Bar(a:Vertex,b:Vertex,left:Boolean,thickness:int = 8,color:uint = 0x000000, mass:int = 100) {			
		super(a,b,thickness,color);
		M = mass;
		this.L = distance();
		trace(L);
		this.left = left;
		
			pivot = a;
			nonPivot = b;
		
		I = M*Math.pow(L,2)/3
		trace(I);
		
		A = T/I;
		theta = 0;
		rotateSystem();
	}		
	
	public function changeAcc(addForce:Boolean):void {
		T = L/2 * (G*M)
		if(addForce)
			T += L * 2500 * (M);
			
		trace(T/I);
		A = T/I * 5;
		if(left)
			A *= -1;
		
		
	}
	
	public function updateBar(dt:Number):void {
		W += A*dt;
		theta += W*dt;
		if(theta < -Math.PI/3 && left) {
			theta = -Math.PI/3;
			W = 0;
		}
		else if(theta > Math.PI/3 && !left) {
			theta = Math.PI/3;
			W = 0;
		}
		else if((theta < 0 && !left) || (theta > 0 && left))
		{
			theta = 0;
			W=0;
		}
		trace(theta + " " +left);
		rotateSystem();
	}
		
		
	private function rotateSystem():void {
			
			// treat center (the pin) as origin of system:
			var tmp1:Vertex = Vertex.sub(pivot,nonPivot);

			// rotate right ball about center:
			var tmp2:Vertex = rotateVertex(tmp1,theta); // use current angle

			// translate right ball relative to actual position (the pin):
			var tmp3:Vertex = Vertex.add(pivot,tmp2);
			
			/// update ball positions:
			//rightBall.x = tmp3.x;
			//rightBall.y = tmp3.y;

			// update bar:
			update(pivot,tmp3);
		}
		
		private function rotateVertex(old:Vertex,angle:Number):Vertex {
			var sin:Number = Math.sin(angle);
			var cos:Number = Math.cos(angle);
			var Xnew:Number = cos*old.x-sin*old.y;
			var Ynew:Number = sin*old.x+cos*old.y;
			return new Vertex(Xnew,Ynew);
		}

	}
	
}
